#include<bits/stdc++.h>
#define ll long long
using namespace std;
struct kkk {
	ll in, out;
} d[10];
ll n, m;
char num;
string f;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	freopen("hw.in", "r", stdin);
	freopen("hw.out", "w", stdout);
	cin >> n >> m;
	cin >> f;
	for (int i = 0; i < n; i++) {
		cin >> num;
		cin >> d[num].in >> d[num].out;
	}
	ll ans = 1e13;
	if (f[0] == f[2]) {
		ans = 0;
	}
	if (f[0] == f[1]) {
		ans = min(ans, d[f[3]].out);
	}
	if (f[1] == f[2]) {
		ans = min(ans, d[f[1]].out);
	}
	if (f[1] != f[2] && f[2] != f[0] && f[0] != f[1]) {
		ans = min(d[f[1]].out + d[f[2]].out, ans);
		ans = min(d[f[2]].out + d[f[0]].out, ans);
		ans = min(d[f[1]].out + d[f[0]].out, ans);
		ans = min(d[f[1]].in + d[f[2]].in, ans);
		ans = min(d[f[0]].in + d[f[2]].in, ans);
		ans = min(d[f[1]].in + d[f[0]].in, ans);
	}
	cout<<ans;



	return 0;
}
